﻿using System;
using System.Linq;
using Pap.Data;
using Pap.Data.Abstraction.Utils;

namespace Pap.Services.Customer
{
    /// <summary>
    /// 
    /// </summary>
    public class PreviousTrials : CustomerValidatorBase
    {
        /// <summary>
        /// 
        /// </summary>
        ILookUpRepository lookupRepository;
        /// <summary>
        /// Initializes a new instance of the <see cref="PreviousTrials"/> class.
        /// </summary>
        /// <param name="_db">The _DB.</param>
        /// <param name="lookupRepo">The lookup repo.</param>
        public PreviousTrials(IDatabase _db, ILookUpRepository lookupRepo)
            : base(_db)
        {
            isError = false;
            canValidateByName = true;
            this.lookupRepository = lookupRepo;
        }

        /// <summary>
        /// Validates the specified current committee ID.
        /// </summary>
        /// <param name="currentCommitteeID">The current committee ID.</param>
        /// <param name="customer">The customer.</param>
        /// <returns></returns>
        public override bool Validate(Guid currentCommitteeID, Pap.Data.ICustomer customer)
        {
            bool hasTrials = false;
            var priviousTrialsCloseTypesIDs = lookupRepository.GetPreviousTrialsCloseType().Select(lookup => lookup.ID);
            if (priviousTrialsCloseTypesIDs.Count() > 0)
            {
                hasTrials = (from loan in _database.CustomerLoans
                             join loanHistory in _database.CustomerLoanHistories
                             on loan.LoanID equals loanHistory.LoanID
                             where loan.CustomerID == customer.CustomerID && priviousTrialsCloseTypesIDs.Contains(loanHistory.LoanHistoryCloseTypeID.Value)
                             select loan.LoanAmount).Count() > 0;
            }
            return !hasTrials;
        }

        /// <summary>
        /// Validates the specified current committee ID.
        /// </summary>
        /// <param name="currentCommitteeID">The current committee ID.</param>
        /// <param name="customerName">Name of the customer.</param>
        /// <returns></returns>
        public override bool Validate(Guid currentCommitteeID, string customerName)
        {
            var priviousTrialsCloseTypesIDs = lookupRepository.GetPreviousTrialsCloseType().Select(lookup => lookup.ID);
            bool hasTrials = (from loanHistory in _database.CustomerLoanHistories
                              where loanHistory.CustomerName.Contains(customerName) && priviousTrialsCloseTypesIDs.Contains(loanHistory.LoanHistoryCloseTypeID.Value)
                              select loanHistory.LoanHistoryID).Count() > 0;
            return !hasTrials;
        }
    }
}
